package com.hjt.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hjt.common.to.es.SkuEsModel;
import com.hjt.gulimall.search.config.ElasticConfig;
import com.hjt.gulimall.search.constant.EsConstant;
import com.hjt.gulimall.search.exception.ProductUpException;
import com.hjt.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 商品信息保存
 * @author:97007
 * @date:2021/9/19 23:42
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restClient;

    // 商品上架
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws ProductUpException {
        // 给es中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        // 设置批量请求的内容
        for (SkuEsModel skuEsModel : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString()); // 设置索引Id
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse response;
        try {
            response = restClient.bulk(bulkRequest, ElasticConfig.COMMON_OPTIONS);
        } catch (IOException ioException) {
            throw new ProductUpException("商品上架失败",ioException);
        }

        // 输出失败信息
        Arrays.stream(response.getItems()).forEach(item -> {
            if (item.isFailed()) {
                log.error("保存sku信息失败，skuId:{}", item.getId());
            }
        });
       return !response.hasFailures() ;
    }
}
